<template>
    <div>
        <el-breadcrumb separator-class="el-icon-caret-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区-->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showCateDialog">添加分类</el-button>
                </el-col>
            </el-row>


            <!--表格-->
            <tree-table class="treeTable" :data="cateList" :columns="columns" :selection-type="false"
                        :expand-type="false"
                        show-index index-text="#" border>
                <template slot="isOK" slot-scope="scope">
                    <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
                    <i class="el-icon-error" v-else style="color: red"></i>
                </template>

                <template slot="sort" slot-scope="scope">
                    <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
                    <el-tag v-else-if="scope.row.cat_level === 1" type="success" size="mini">二级</el-tag>
                    <el-tag v-else type="warning" size="mini">三级</el-tag>
                </template>

                <template slot="operation" slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="editCateById(scope.row)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteCateById(scope.row.cat_id)"></el-button>
                </template>

            </tree-table>


            <!--分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[3, 5, 10, 15]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>

            <!--添加分类的对话框-->
            <el-dialog title="添加分类" :visible="setCateDialog"
                       @close="closeCateDialog" width="50%">
                <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
                    <el-form-item label="分类名称" prop="cat_name">
                        <el-input v-model="addCateForm.cat_name"></el-input>
                    </el-form-item>
                    <el-form-item label="父级分类">
                        <el-cascader
                                v-model="selectedKeys"
                                :options="parentCateList"
                                :props="cascaderProperties"
                                @change="parentCateChange"
                                clearable
                                >
                        </el-cascader>
                    </el-form-item>
                </el-form>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="setCateDialog = false">取 消</el-button>
                    <el-button type="primary" @click="addCate">确 定</el-button>
                  </span>
            </el-dialog>

            <!--编辑分类弹出框-->
            <el-dialog title="编辑分类" :visible="setEditCateDialog"
                       @close="closeCateDialog" width="50%">
                <el-form :model="addCateForm" :rules="addCateFormRules" ref="editCateFormRef" label-width="100px">
                    <el-form-item label="分类名称" prop="cat_name">
                        <el-input v-model="addCateForm.cat_name"></el-input>
                    </el-form-item>
                </el-form>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="setEditCateDialog = false">取 消</el-button>
                    <el-button type="primary" @click="saveEditCate">确 定</el-button>
                  </span>
            </el-dialog>
        </el-card>

    </div>
</template>

<script>
    export default {
        name: "Cate",
        data() {
            return {
                //商品分类的数据列表
                cateList: [],

                queryInfo: {
                    type: 3,
                    pagenum: 1,
                    pagesize: 5
                },

                //定义商品分类的总记录数
                total: 0,

                //为table指定列的定义
                columns: [{
                    label: '分类名称',
                    prop: 'cat_name'
                },
                    {
                        label: '是否有效',
                        type: 'template',
                        //表示当前列使用的模板名称
                        template: 'isOK'
                    },
                    {
                        label: '排序',
                        type: 'template',
                        //表示当前列使用的模板名称
                        template: 'sort'
                    },
                    {
                        label: '操作',
                        type: 'template',
                        //表示当前列使用的模板名称
                        template: 'operation'
                    },
                ],

                //设置新增分类对话框的显示
                setCateDialog: false,

                //添加分类的表单数据对象
                addCateForm: {
                    cat_name : '',
                    //分类父 ID
                    cat_pid : 0,
                    //默认添加的是一级分类
                    cat_level: 0
                },

                addCateFormRules: {
                    cat_name: [
                        {required: true, trigger: 'blur', message:'请输入分类的名称'}
                    ]
                },

                //父级分类的列表
                parentCateList: [],

                //级联选择框中的属性
                cascaderProperties: {
                    expandTrigger : 'hover',
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children',
                    checkStrictly: true,
                },

                //选中符集分类的数组
                selectedKeys: [],

                //编辑分类的对话框的显示
                setEditCateDialog: false,

            }
        },
        created() {
            this.getCateList();
        },
        methods: {
            //获取商品分类的列表
            async getCateList() {
                const {data} = await this.$http.get('categories', {params: this.queryInfo});
                if (data.meta.status !== 200) return this.$message.error('获取商品分类失败');
                this.cateList = data.data.result;
                this.total = data.data.total;
            },

            //处理pagesize改变的事件
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize;
                this.getCateList();
            },

            //监听pagenum的变化
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage;
                this.getCateList();
            },

            //点击按钮显示对话框
            showCateDialog(){
                //获取父级分类的数据列表，然后展示对话框
                this.getParentCateList();
                this.setCateDialog = true;
            },

            //获取父级分类的数据列表
            async getParentCateList(){
                const {data} = await this.$http.get('categories',{params:{type: 2}});
                if (data.meta.status !== 200) return this.$message.error('获取父级分类失败');
                this.parentCateList = data.data;
            },

            //级联选择框发生变化时触发的函数
            parentCateChange(){
                //如果selectedKeys 中的长度大于0，则选中了父级分类，父级分类永远是最后一项
                if (this.selectedKeys.length > 0){
                    this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
                    //为当前分类的等级赋值
                    this.addCateForm.cat_level = this.selectedKeys.length;
                }else {
                    this.addCateForm.cat_pid = 0;
                    this.addCateForm.cat_level = 0;
                }
            },

            //点击按钮添加新的分类
            addCate(){
                this.$refs.addCateFormRef.validate(async valid => {
                    if (valid){
                        const {data} = await this.$http.post('categories',this.addCateForm);
                        if (data.meta.status !== 201) return this.$message.error('添加分类失败');
                        this.getCateList();
                        this.setCateDialog = false;
                        this.$message.success('添加分类成功');
                    }
                })
            },

            //监听弹出框的关闭
            closeCateDialog(){
                this.selectedKeys = [];
                this.addCateForm = {cat_level: 0, cat_pid: 0};
                this.setCateDialog = false;
                this.setEditCateDialog = false;
            },

            //根据Id修改对应的cate
             async editCateById(cateRow){
                const {data} = await this.$http.get(`categories/${cateRow.cat_id}`);
                if (data.meta.status !== 200) return this.$message.error('查询分类失败');
                this.addCateForm = data.data;
                this.setEditCateDialog = true;
            },

            //点击按钮保存修改
            saveEditCate(){
                this.$refs.editCateFormRef.validate(async valid => {
                    if (valid){
                        const {data} = await this.$http.put(`categories/${this.addCateForm.cat_id}`, {cat_name: this.addCateForm.cat_name});
                        if (data.meta.status !== 200)return this.$message.error(data.meta.msg);
                        this.getCateList();
                        this.setEditCateDialog = false;
                        this.$message.success('更新分类成功');
                    }
                })
            },

            //点击按钮删除对应的cate列
            async deleteCateById(id){
                const result = await this.$confirm('您确定要删除该列数据吗','警告',{
                    type: 'error',
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                }).catch(err => err);
                if (result === 'cancel') return this.$message.info('取消删除');
                const {data} = await this.$http.delete(`categories/${id}`);
                if (data.meta.status !== 200)return this.$message.error(data.meta.msg);
                this.getCateList();
                this.$message.success('删除成功');
            },
        }
    }
</script>

<style scoped lang="less">

    .treeTable {
        margin-top: 15px;
        margin-bottom: 15px;
    }
    .el-cascader{
        width: 100%;
    }

</style>
